import os
import subprocess
import tempfile
import common.io_utils.dirs as io_dirs
import common.io_utils.archivals as io_arch

if __name__ == "__main__":
    # Should implement logger
    print("Testing parallel download")
    # Create test folders
    with tempfile.TemporaryDirectory() as Temp_Working_Path:
        print("created temporary directory", Temp_Working_Path)
        Testing_Folder_Path_zip = os.path.join(Temp_Working_Path, "zips")
        Testing_Folder_Path_out = os.path.join(Temp_Working_Path, "out")
        io_dirs.mkdir_p(Temp_Working_Path)
        io_dirs.mkdir_p(Testing_Folder_Path_zip)
        io_dirs.mkdir_p(Testing_Folder_Path_out)
        # Download some compressed files
        # (e.g. EU car emission data https://www.eea.europa.eu/data-and-maps/data/co2-cars-emission-7)
        base_url = "https://www.eea.europa.eu/data-and-maps/data/co2-cars-emission-7/monitoring-of-co2-emissions-from"
        sub_paths = [
            "-2010-final/ascii-delimited-zip/at_download/file",
            "-2011-provisional/CO2_passenger_cars_v3_csv/at_download/file",
            "-2011-final/ascii-delimited-zip/at_downlosad/file",
            "-2013-final/co2_passenger_cars_v8_mdb.zip/at_download/file",
        ]
        download_list = [base_url + sub_path for sub_path in sub_paths]

        file_count = 0
        with io_dirs.working_directory(Testing_Folder_Path_zip):
            for url in download_list:
                file_count += 1
                commands = ["wget", "-O", f"file_{file_count}.zip", url]
                subprocess.run(commands)
        lst_fpaths = os.listdir(Testing_Folder_Path_zip)
        print(f"Downloaded files: {lst_fpaths}")
        nproc = 2
        dir_dest = Testing_Folder_Path_out
        with io_dirs.working_directory(Testing_Folder_Path_zip):
            io_arch.unzip_batch(lst_fpaths, dir_dest, nproc)
        lst_fpaths2 = os.listdir(Testing_Folder_Path_out)
        print(f"Extracted files: {lst_fpaths2}")
        print(
            f"Test completed, temp folder {Temp_Working_Path} will be automatically upon closing program."
        )
